package team.star.werespos.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import team.star.werespos.mapper.PermissionMapper;
import team.star.werespos.exception.GlobalException;
import team.star.werespos.model.entity.Permission;
import team.star.werespos.model.enums.CodeMsgEnum;
import team.star.werespos.service.PermissionService;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * PermissionServiceImpl class<br/>
 *
 * @author CAI
 * @since 2019/04/09
 */
@Slf4j
@Service
public class PermissionServiceImpl implements PermissionService {

    @Resource
    private PermissionMapper permissionMapper;

    @Override
    public void insertOne(Permission permission) {
        // 非空检查
        Preconditions.checkNotNull(permission, "permission is null!");
        // 新增
        Optional.ofNullable(permissionMapper.insert(permission))
                .ifPresent(result -> {
                    if (result == 0) {
                        log.error("【新增权限】失败！result = [{}], permission = [{}]",
                                result, permission);
                        throw GlobalException.create(CodeMsgEnum.DATABASE_EXCEPTION);
                    }
                });
    }

    @Override
    public List<Permission> listPermission() {
        return permissionMapper.selectList(
                new QueryWrapper<>()
        );
    }

    @Override
    public void updateById(Permission permission) {
        Optional.ofNullable(permissionMapper.updateById(permission))
                .ifPresent(result -> {
                    if (result == 0) {
                        log.error("【修改权限】失败！result = [{}], permission = [{}]",
                                result, permission);
                        throw GlobalException.create(CodeMsgEnum.DATABASE_EXCEPTION);
                    }
                });
    }

    @Override
    public void deleteById(Permission permission) {
        Optional.ofNullable(permissionMapper.deleteById(permission))
                .ifPresent(result -> {
                    if (result == 0) {
                        log.error("【删除权限】失败！result = [{}], permission = [{}]",
                                result, permission);
                        throw GlobalException.create(CodeMsgEnum.DATABASE_EXCEPTION);
                    }
                });
    }

}
